Random¶

🖌 random¶

NOTES

  • For each example, demonstrate how running the code again yields different results

random.choice()¶

In [16]:
import random

fruits = ['pear','mango','banana','strawberry','kumquat']
selection = random.choice(fruits)
print(selection)
banana

random.randint()¶

In [38]:
import random

print(random.randint(1, 10))
10

NOTES

  • Note that random.randint() can return the boundary numbers
    • so, the return number is anything including and between the arguments.

random.random()¶

In [69]:
print(random.random())
0.5002419706259531

If you need a random float between 0 and 100, just scale the random number:

In [70]:
print(random.random() * 100)
88.10581258132582

random.sample()¶

In [94]:
name = 'George Washington'
In [95]:
print(random.sample(name, 2))
['t', 'a']
In [96]:
print(random.sample(name, 5))
['a', 's', 'g', 'g', 't']
In [101]:
print(random.sample(name, len(name)))
['n', 'r', 's', 'G', 'n', 't', 'e', ' ', 'g', 'W', 'i', 'a', 'g', 'e', 'o', 'h', 'o']

🖌 Shuffle¶

random.sample can be used to get a random sample from a collection.

If you sample all the items in the collection, you essentially get a shuffled version of the data.

In [102]:
import random

def shuffle(string):
    """
    Use random.sample to get the letters in the string in a random order.
    Then join the letters together with the empty string.
    """
    shuffled_letters = random.sample(string, len(string))
    return ''.join(shuffled_letters)
In [114]:
shuffle('12345')
Out[114]:
'54123'
In [126]:
shuffle('CS110')
Out[126]:
'1CS10'

🖌 Random events at some frequency¶

apples.py¶

🧑🏼‍🎨 Umm...¶

Write a program that takes a frequency (a number between 0 and 1) and a phrase as commandline arguments.

Randomly inject "umm" into a given sentence at the given frequency and print the result.

umm.py¶

NOTES

  • Draw it out!
    • Sentence -> words -> words with umm -> sentence
python umm.py 0.2 'So, I've been meaning to ask, will you go out on a date with me?'

Key Ideas¶

  • random
    • choice
    • randint
    • random
    • sample
  • Shuffling strings using random.sample
  • Random events at some frequency